<?PHP
require_once('cls_mysql.php');
if( empty($GLOBLS['db']) )
	$db = new cls_mysql(BTC_DB_HOST,  BTC_DB_USER, BTC_DB_PASS, BTC_DB_NAME);

function updateOnlineBuySell( $pair, $buy, $sell )
{
	$sql = "UPDATE rules SET online_buy_price=".$buy.", online_sell_price=".$sell.
			" WHERE pair='".$pair."'";
	$GLOBALS['db']->query( $sql );
}
/**
 * 获取所有待sell的订单
 * @return array( pair=>Array( orders....), pair=>...);bool
 */
function getToSellOrders()
{
	$sql = "SELECT * FROM order_list WHERE pre_sell_rate > 0 AND `status`=".BTC_ORDER_STATUS_FILLED.
			" AND `type` = '".BTC_TRADE_TYPE_BUY."' AND ref_id=0";
	$result = $GLOBALS['db']->getAll( $sql );
	if( empty($result) ) return false;
	foreach( $result AS $i=>$row )
	{
		$result[$row['pair']][] = $row;
		unset($result[$i]);
	}
	return $result;
}
/**
 * 将buy订单挂上
 */
function sellOrder($order_id,$sell_id)
{
	$sql = "UPDATE order_list SET ref_id=".$sell_id." WHERE order_id=".$order_id;
	return $GLOBALS['db']->query( $sql );
}
function cancelSell($sell_id)
{
	// 将原订单标识为可继续售卖
	$sql = "UPDATE order_list SET ref_id=0 WHERE `type`=".BTC_TRADE_TYPE_BUY." AND ref_id=".$sell_id;
	$GLOBALS['db']->query( $sql );

	// 作废售单
	$sql = "UPDATE order_list set `status`=".BTC_ORDER_STATUS_CANCEL.
			" WHERE `type`=".BTC_TRADE_TYPE_SELL." AND order_id=".$sell_id;
	return $GLOBALS['db']->query( $sql );
}
/**
 * 作废订单
 */
function cancelOrder( $order_id )
{
	$sql = "UPDATE order_list SET `status`=".BTC_ORDER_STATUS_CANCEL." WHERE order_id=".$order_id;
	$GLOBALS['db']->query( $sql );
}
/**
 * 获得将要作废的订单
 */
function getToCancelOrders()
{
	$sql = "SELECT * FROM order_list WHERE to_cancel=".BTC_ORDER_TO_CANCEL;
	return $GLOBALS['db']->getAll( $sql );
}
/**
 * 根据线上最新的交易，看下买哪些订单
 * @param $rule 规则
 * @param 要买多少订单数
 */
function getRateAmountToBuys( $rule, $num )
{
	// 买/卖比例 ，从买or卖中读取数据
	$bsPercent=0.5;
	$buyNum = ceil($num*$bsPercent);
	$sellNum = $num - $buyNum;
	$buyAry = _getRateAmountToBuys( $rule['pair'], BTC_PEOPLE_BUY, $buyNum );
	$sellAry = _getRateAmountToBuys( $rule['pair'], BTC_PEOPLE_SELL, $sellNum );
	return array_merge($buyAry,$sellAry);
}
/**
 * 从买、卖中取得要下哪些订单
 * @param unknown_type $pair
 * @param unknown_type $type
 * @param unknown_type $amount 要购买的数量
 */
function _getRateAmountToBuys( $pair, $type, $amount, $limit=20 )
{
	$orderBy = Array(BTC_PEOPLE_BUY=>'DESC',BTC_PEOPLE_SELL=>'ASC');
	$sumAmount = 0;
	$return = Array();
	$sql = "SELECT price,amount FROM online_trades WHERE pair='".$pair."'
			AND type='".$type."' ORDER BY trans_id ".$orderBy[$type]." LIMIT ".$limit;
	$result = $GLOBALS['db']->getAll($sql);
	if( empty($result) )return $return;
	else
	{
		foreach( $result AS $row )
		{
			$n = $amount - $sumAmount;
			$sumAmount += $row['amount'];
			if( $sumAmount <= $amount )
				array_push($return, $row);
			else
			{
				if( $n > 0.01 )
				{
					$row['amount'] = $n;
					array_push( $return, $row );
				}
				break;
			}
		}

	}
	return $return;
}
/**
 * @param 当前可用的pair
 */
function getMaxTransIdByPairs($pairs)
{
	$sql = "SELECT pair,max(trans_id) as trans_id FROM online_trades
			WHERE timestamp_created > UNIX_TIMESTAMP()-120000
				AND pair in ('".implode("','",$pairs)."')
				GROUP BY pair";
	return $GLOBALS['db']->getAll( $sql );
}

/**
 * 将线上的取得的PAIR交易插入DB中
 * @param string $pair
 * @param array $rows
 * @param integer $max_trans_id
 * @return 插入系统中的数量
 */
function insertOnlineTrade($pair, array $rows, $max_trans_id)
{
	if ( empty($max_trans_id) ) $max_trans_id = 0;
	$sql = "INSERT INTO online_trades ( trans_id, pair, price, amount,
			 `type`, timestamp_created ) VALUES ";
	$i=0;
	foreach( $rows AS $row )
	{
		if( $row['tid'] > $max_trans_id )
		{
			if( $i>0 ) $sql .= ",";
			$sql .= "(".$row['tid'].",'".$pair."',".$row['price'].','.$row['amount'].
					",'".$row['trade_type']."',".$row['date'].")";
			$i++;
		}
	}

	if( $i>0 )
		$GLOBALS['db']->query( $sql );
	return $i;
}
// 获得规则可购买的数量
function getBuyNum($rule, $user)
{
	// if can't buy, then return 0
	if( $rule['can_buy'] == BTC_RULE_CANOT_BUY ) return 0;

	// money name
	$tmpAry = explode('_', $rule['pair']);
	$payMoney = $tmpAry[1];

	// name money
	$pay = moneyFormat($user[$payMoney]);

	// money can pay num
	$moneyCanBuyNum = ceil($pay/$rule['online_buy_price']);

// 	// limit num
// 	$limitNum = min($rule['min_num'],$rule['max_active_num']-$rule['active_num']);

	return min( $rule['buy_unit'], $moneyCanBuyNum );
}

// 获得所有的RULE
function getAllRules()
{
	$sql = "SELECT * FROM rules WHERE in_use=".BTC_RULE_IN_USE;
	return $GLOBALS['db']->getAll( $sql );
}
function updateBtcAccount($row)
{
	$sql = "UPDATE funds SET ".
				"usd=". $row['funds']['usd'].",rur=". $row['funds']['rur'].
				",ltc=". $row['funds']['ltc'].",trc=". $row['funds']['trc'].
				",ppc=". $row['funds']['ppc'].",nmc=". $row['funds']['nmc'].
				",eur=". $row['funds']['eur'].",nvc=". $row['funds']['nvc'].
				",btc=". $row['funds']['btc'].",right_info=". $row['right_info'].
				",right_trade=". $row['right_trade'].",right_withdraw=". $row['right_withdraw'].
				",transaction_count=". $row['transaction_count'].",open_orders=". $row['open_orders'].
				",date_update='".$row['date_update']."'".
			" WHERE user='".$row['user']."' AND id=".$row['user_id'];
	return $GLOBALS['db']->query($sql);
}
//获得某一个账号
function getBtcAccount( $user )
{
	$res = getBtcAccounts( $user );
	if( !empty($res) )return $res[0];
	else return false;
}
// 获取所有可用的BTC账号
function getBtcAccounts($user='')
{
	$sql = "SELECT * from funds WHERE in_use=".BTC_ACCOUNT_OK.(empty($user)?'':" AND user='".$user."'");
	return $GLOBALS['db']->getAll( $sql );
}
// 插入历史交易
function insertTransHistory($row)
{
	$fields['trans_id'] = $row['trans_id'];
	$fields['type'] = $row['type'];
	$fields['amount'] = $row['amount'];
	$fields['currency'] = "'".$row['currency']."'";
	$fields['`desc`'] = "'".$row['desc']."'";
	$fields['timestamp'] = $row['timestamp'];

	$sql = "insert into trans_history(".implode(',',array_keys($fields)).") VALUES ".
			"(".implode(',',array_values($fields)).")";
	return $GLOBALS['db']->query($sql);
}
/**
 * 如果订单已经存在，更新其状态
 * @param unknown_type $row
 * @return boolean TRUE:存在且已更新，FALSE：不存在
 */
function existsOrderAndUpdate($row)
{
	$sql = "SELECT 1 FROM order_list WHERE order_id=".$row['order_id'];
	if( $GLOBALS['db']->getOne($sql)==1 )
	{
		$sql = "UPDATE order_list SET `status`=".$row['status']." WHERE order_id=".$row['order_id'];
		$GLOBALS['db']->query( $sql );
		return true;
	}
	else return false;
}
// 插入订单
function insertOrder($row)
{
	global $btc_trade_types;

	$fields['order_id'] = $row['order_id'];
	$fields['type'] = "'".$row['type']."'";
	$fields['amount'] = $row['amount'];
	$fields['rate'] = $row['rate'];
	$fields['status'] = $row['status'];
	$fields['timestamp_created'] = $row['timestamp_created'];
	$fields['pair'] = "'".$row['pair']."'";
	$fields['date_insert'] = "'".@date('Y-m-d H:i:s')."'";
	if( $row['type'] == BTC_TRADE_TYPE_SELL &&
			 in_array($row['status'],array(BTC_ORDER_STATUS_TODO,BTC_ORDER_STATUS_FILLED)) )
	{
		$sql = "UPDATE order_list SET ref_id=".$row['order_id'].
				" WHERE `status`=".BTC_ORDER_STATUS_FILLED.
				" AND `type`='".BTC_TRADE_TYPE_BUY."'".
				" AND amount=".$row['amount'].
				" AND pair='".$row['pair']."' LIMIT 1";
	}

	$sql = "insert into order_list(".implode(',',array_keys($fields)).") VALUES ".
			"(".implode(',',array_values($fields)).")";
	return $GLOBALS['db']->query($sql);
}
// 插入交易
function insertTradeHistory($row)
{
	global $btc_trade_types;

	$fields['trans_id'] = $row['trans_id'];
	$fields['order_id'] = $row['order_id'];
	$fields['type'] = $btc_trade_types[$row['type']];
	$fields['amount'] = $row['amount'];
	$fields['rate'] = $row['rate'];
	$fields['time'] = $row['timestamp'];
	$fields['pair'] = "'".$row['pair']."'";
	$fields['date_insert'] = "'".@date('Y-m-d H:i:s')."'";


	$sql = "insert into trade_history(".implode(',',array_keys($fields)).") VALUES ".
			"(".implode(',',array_values($fields)).")";
	return $GLOBALS['db']->query($sql);
}

function logBtcApiResult( $method, $msg )
{
	$sql = "insert into api_result(method, msg, date_insert) values('".$method."', '".$msg."',NOW())";
	return $GLOBALS['db']->query($sql);
}
//
// 从历史交易就获取最大的交易
function getMaxTransId($tbl_name=BTC_TABLE_TRANS,$field=BTC_FIELD_TRANS_ID)
{
	$sql = "select ".$field." from ".$tbl_name." order by id DESC limit 1";
	return $GLOBALS['db']->getOne($sql);
}
// 从取得所有等待处理的订单ID
function getMaxOrderId()
{
	$sql = "SELECT order_id FROM order_list where `status`=".BTC_ORDER_STATUS_TODO.
			" ORDER BY order_id ASC LIMIT 1";
	$order_id = $GLOBALS['db']->getOne($sql);
	if ( !empty($order_id) ) return $order_id;
	$sql = "SELECT max(order_id) FROM order_list where 1".
			" ORDER BY order_id DESC LIMIT 1";
	return $GLOBALS['db']->getOne($sql)+1;
}
// btc api interface
function btce_query($method, array $req = array())
{
	$key = BTC_API_KEY; // your API-key
	$secret = BTC_API_SRT; // your Secret-key
	// API settings
	if( isset($req['key']) && isset($req['srt']))
	{
		$key = $req['key'];unset($req['key']);
		$secret = $req['srt'];unset($req['srt']);
	}


	$req['method'] = $method;
	$mt = explode(' ', microtime());
	$req['nonce'] = $mt[1];

	// generate the POST data string
	$post_data = http_build_query($req, '', '&');

	$sign = hash_hmac("sha512", $post_data, $secret);

	// generate the extra headers
	$headers = array(
		'Sign: '.$sign,
		'Key: '.$key,
	);

	// our curl handle (initialize if required)
	static $ch = null;
	if (is_null($ch)) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; BTCE PHP client; '.php_uname('s').'; PHP/'.phpversion().')');
	}
	curl_setopt($ch, CURLOPT_URL, 'https://btc-e.com/tapi/');
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

	// run the query
	$res = curl_exec($ch);
	if ($res === false) throw new Exception('Could not get reply: '.curl_error($ch));
	$dec = json_decode($res, true);
	if (!$dec) throw new Exception('Invalid data received, please make sure connection is working and requested API exists');
	return $dec;
}

/**
 * 通过public api 取得所有的买卖交易
 * @param unknown_type $pair
 */
function btce_trades($pair)
{
	$btec_api = "https://btc-e.com/api/2/".$pair."/trades";

	// our curl handle (initialize if required)
	static $ch = null;
	if (is_null($ch)) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; BTCE PHP client; '.php_uname('s').'; PHP/'.phpversion().')');
	}
	curl_setopt($ch, CURLOPT_URL, $btec_api);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

	// run the query
	$res = curl_exec($ch);
	if ($res === false) throw new Exception('Could not get reply: '.curl_error($ch));
	$dec = json_decode($res, true);
	if (!$dec) throw new Exception('Invalid data received, please make sure connection is working and requested API exists');
	return $dec;

}

/**
 * 通过public api 取得所有的买卖交易
 * @param unknown_type $pair
 */
function btce_tickers($pair)
{
	$btec_api = "https://btc-e.com/api/2/".$pair."/ticker";

	// our curl handle (initialize if required)
	static $ch = null;
	if (is_null($ch)) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; BTCE PHP client; '.php_uname('s').'; PHP/'.phpversion().')');
	}
	curl_setopt($ch, CURLOPT_URL, $btec_api);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

	// run the query
	$res = curl_exec($ch);
	if ($res === false) throw new Exception('Could not get reply: '.curl_error($ch));
	$dec = json_decode($res, true);
	if (!$dec) throw new Exception('Invalid data received, please make sure connection is working and requested API exists');
	return $dec;
}

function moneyFormat($val)
{
	if( empty($val) )return $val=0;
	return sprintf("%5.8f",$val);
}
?>
